package com.csu.csumall.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.csu.csumall.VO.CartVO;
import com.csu.csumall.common.OrderStatus;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Order {

    @TableId(value = "id", type= IdType.AUTO)
    private Integer id;
    private BigInteger orderNo;
    private Integer userId;
    private Integer shippingId;
    private Integer paymentPrice;
    private Integer paymentType;
    private Integer postage;
    private Integer status;
    private LocalDateTime paymentTime;
    private LocalDateTime sendTime;
    private LocalDateTime endTime;
    private LocalDateTime closeTime;
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
    @TableField(fill = FieldFill.UPDATE)
    private LocalDateTime updateTime;

    @JsonIgnore
    public boolean isEnoughToSave() {
        return null != shippingId && null != postage;
    }

    /**
     * 创建订单
     * @return
     */
    @JsonIgnore
    public Order(Integer userId) {
        orderNo = newOrderNo();
        this.userId = userId;
        status = OrderStatus.UN_PAYED.getValue();
    }

    @JsonIgnore
    public void updateOrder() {
        userId = null;
        updateTime = LocalDateTime.now();
    }

    @JsonIgnore
    public void updateUpdateTime() {
        updateTime = LocalDateTime.now();
    }

    @JsonIgnore
    public BigInteger newOrderNo() {
        LocalDateTime localDateTime = LocalDateTime.now();
        String timeStr = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmSS"));
        Integer randNum = new Random().nextInt(999999);
        return new BigInteger(timeStr + randNum);
    }
}

